<?php

namespace Helpers;

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\SoftDelete;
use Helpers\User;

class BaseModel extends Model
{

    /**
     * 初始化软删除
     *
     * create by ck 20181121
     * modify by ck 20181227    兼容老model
     */
    public function initialize()
    {
        $this->useDynamicUpdate(true);
//        $this->keepSnapshots(false);
        if (property_exists($this, 'isDel')) {
            $this->addBehavior(new SoftDelete([
                'field' => 'isDel',
                'value' => 1,
            ]));
        }
        $this->initializeOld();
    }

    /**
     * 获取保存错误原因
     *
     * @return string
     *
     * create by ck 20181121
     */
    public function getError()
    {
        $message = parent::getMessages()[0];
        return $message->getMessage();
    }

    /**
     * 根据id删除记录
     *
     * @param $ids
     * @return mixed
     * @throws \Exception
     *
     * create by ck 20180322
     * modify by ck 20190130
     */
    public static function deleteById(array $ids)
    {
        if (!$ids) {
            throw new \Exception('缺少id');
        }
        return self::find([
            'conditions' => "isDel = 0 AND id IN ({idArr:array})",
            'bind'       => ['idArr' => $ids]
        ])->delete();
    }

    /**
     * 分页获取数据
     *
     * @param array $parameters
     * @param int $page
     * @param int $size
     * @return array
     *
     * create by ck 20190116
     */
    public static function runPage($parameters = [], $page = 1, $size = 50)
    {
        if (is_string($parameters)) {
            $parameters = [
                'conditions' => $parameters
            ];
        }
        $total = self::count($parameters);
        $total = is_int($total) ? $total : count($total->toArray());
        $parameters['limit'] = [
            'number' => $size,
            'offset' => $size * ($page - 1)
        ];
        $rows = self::find($parameters)->toArray();
        return [
            'page'      => $page,
            'totalPage' => ceil($total / $size),
            'size'      => $size,
            'total'     => $total,
            'rows'      => $rows
        ];
    }

    /**
     * 创建前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeCreate()
    {
        $userId  = User::getId();
        $time    = time();
        if (property_exists($this, 'isDel')) {
            $this->writeAttribute('isDel', 0);
        }
        if (property_exists($this, 'createAt')) {
            $this->writeAttribute('createAt', $time);
        }
        if (property_exists($this, 'createBy')) {
            $this->writeAttribute('createBy', $userId);
        }
        if (property_exists($this, 'updateAt')) {
            $this->writeAttribute('updateAt', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'updateBy')) {
            $this->writeAttribute('updateBy', $userId);
        }
        $this->beforeCreateOld();
        return true;
    }

    /**
     * 更新前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeUpdate()
    {
        if (property_exists($this, 'updateAt')) {
            $this->writeAttribute('updateAt', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'updateBy')) {
            $this->writeAttribute('updateBy', User::getId());
        }
        $this->beforeUpdateOld();
        return true;
    }

    /**
     * 删除前记录最后修改时间及操作人
     *
     * @return bool
     *
     * create by ck 20181121
     */
    public function beforeDelete()
    {
        $this->beforeUpdate();
        $this->beforeUpdateOld();
        return true;
    }

    //兼容
    public static function deleteRecord($idField, $idArr)
    {
        if (!$idField || !$idArr || !is_string($idField)) {
            return false;
        }
        is_string($idArr) and $idArr = explode(',', $idArr);
        return self::find([
            'conditions' => "bDelete = 0 AND {$idField} IN ({idArr:array})",
            'bind'       => ['idArr' => $idArr]
        ])->delete();
    }

    //兼容
    public function initializeOld()
    {
        if (property_exists($this, 'bDelete')) {
            $this->addBehavior(new SoftDelete([
                'field' => 'bDelete',
                'value' => 1,
            ]));
        }
    }

    //兼容
    public function beforeCreateOld()
    {
        $userId  = User::getId();
        $time    = date('Y-m-d H:i:s');
        if (property_exists($this, 'bDelete')) {
            $this->writeAttribute('bDelete', 0);
        }
        if (property_exists($this, 'tCreateDate')) {
            $this->writeAttribute('tCreateDate', $time);
        }
        if (property_exists($this, 'iCreateUserId')) {
            $this->writeAttribute('iCreateUserId', $userId);
        }
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', $userId);
        }
        return true;
    }

    //兼容
    public function beforeUpdateOld()
    {
        if (property_exists($this, 'tLastModifyDate')) {
            $this->writeAttribute('tLastModifyDate', date('Y-m-d H:i:s'));
        }
        if (property_exists($this, 'iLastModifyUserId')) {
            $this->writeAttribute('iLastModifyUserId', User::getId());
        }
        return true;
    }

    //兼容
    public function modifyData($new = false)
    {
        return $this->save();
    }

    //兼容
    public function insertData()
    {
        return $this->save();
    }

    //兼容
    public function updateData()
    {
        return $this->save();
    }
}
